package com.young.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * JDBC工具
 * Created by Admin on 2021/6/28.
 */
public class JDBCUtil {

    private static final Logger logger = LoggerFactory.getLogger(JDBCUtil.class);

    /**
     * 获取数据库连接
     * @return Connection 对象
     */
    public static Connection getConnection(String driver, String url, String user, String pwd) {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, pwd);//这里的user和password根据自己的数据库登录和密码填写
        } catch (Throwable e) {
            logger.error("[JDBC工具-获取JDBC链接] 发生异常,driver={},url={},user={},pwd={}", driver, url, user, pwd, e);
        }
        return conn;
    }
    /**
     * 关闭数据库连接
     * @param conn Connection 对象
     */
    public static void closeConnection(Connection conn, PreparedStatement statement, ResultSet rs){
        if (rs != null) {
            try {
                rs.close();
            } catch (Throwable e) {
                logger.error("[JDBC工具-关闭JDBC链接] 关闭ResultSet发生异常", e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Throwable e) {
                logger.error("[JDBC工具-关闭JDBC链接] 关闭statement发生异常", e);
            }
        }
        //判断 conn 是否为空
        if(conn != null){
            try {
                conn.close();//关闭数据库连接
            } catch (Throwable e) {
                logger.error("[JDBC工具-关闭JDBC链接] 关闭链接发生异常", e);
            }
        }
    }
}
